﻿using System;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using ArchivingDataModel;
using System.IO;
using System.Collections.Generic;
using ArchivingDataWebForms.Helpers;
using System.Globalization;

[ServiceBehavior(AddressFilterMode=AddressFilterMode.Any)]
[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class SaveScannedImages
{
	[OperationContract]
	public void DoWork()
	{
		// Add your operation implementation here
		return;
	}

    /// <summary>
    /// this function will take images as  byte array in the form length of images then length of first then first then length of secound then secound ....
    /// </summary>
    /// <param name="btImages">the images</param>
    /// <param name="folder_ID">the attachment_ID to add images to</param>
    /// <returns>a string having the last message or saved images</returns>
    [OperationContract]
    public string saveImages(byte[] btImages , long folder_ID)
    {
        try
        {
            //BLUser blUser = GlobalVars.getLoginUser();

            //if (blUser == null)
            //    return "خطأ , ليس لك صلاحية لاضافة صور";

            //if (blUser.User_ID == null)
            //    return "خطأ , ليس لك صلاحية لاضافة صور";


            //if ((!blUser.HasRule(RulesEnum.Page___Wared_Edit___Action___Save)) && (!blUser.HasRule(RulesEnum.Page___Sader_Edit___Action___Save)))
            //    return "خطأ , ليس لك صلاحية لاضافة صور";

           
            MemoryStream ms = new MemoryStream(btImages);
            byte[] btCount = new byte[4];

            ms.Read(btCount, 0, 4);

            int Count = BitConverter.ToInt32(btCount, 0);


            if (Count == 0)
            {
                return "خطأ , لا يوجد صور تم مسحها من الماسح الالكتروني";
            }


            List<byte[]> lstImages = new List<byte[]>();

            for (int i = 0; i < Count; i++)
            {
                byte[] btLength = new byte[4];
                ms.Read(btLength, 0, 4);

                int length = BitConverter.ToInt32(btLength, 0);

                byte[] btImage = new byte[length];

                ms.Read(btImage, 0, btImage.Length);

                lstImages.Add(btImage);

            }

            ms.Close();
            using (ArchivingDataEntities ent = new ArchivingDataEntities())
            {
                Folder currentfolder = ent.Folders.FirstOrDefault(i => i.Folder_ID == folder_ID);
                ArchivingDataModel.File newFile = new ArchivingDataModel.File()
                {
                    Folder = currentfolder,
                    File_Code = "",
                    File_Order = currentfolder.Files.Count() + 1,
                    FileTitle_Ar = "ملف جديد ",
                    FileTitle_En = "new file",
                    FileSubject_Ar = "ملف جديد ",
                    FileSubject_En = "new file",
                    FileNote_Ar = "ملف جديد من الماسح الضوئي بتاريخ"+DateTime.Now.ToString("dd/MM/yyyyy HH:mm:ss"),
                    FileNote_En = "new File from scanner With date" + DateTime.Now.ToString("dd/MM/yyyyy HH:mm:ss"),
                    FromDate = null,
                    ToDate = null,
                    Is_RecycleBin = false
                };
                newFile.File_UniqueText = WebHelper.Helpers.StringHelper.ToUniqueStatement(newFile.File_Code + newFile.FileTitle_Ar + newFile.FileTitle_En + newFile.FileSubject_Ar + newFile.FileSubject_En + newFile.FileNote_Ar + newFile.FileNote_En);
                ent.AddToFiles(newFile);
                ent.SaveChanges();
                foreach (byte[] btBytes in lstImages)
                {
                    //attachment
                    Attachment newAttachment = new Attachment
                    {
                        Attachment_Order = newFile.Attachments.Count()+1,
                        Attachment_Code = "",
                        AttachmentTitle_Ar = (newFile.Attachments.Count() + 1).ToString(),
                        AttachmentNote_Ar = (newFile.Attachments.Count() + 1).ToString(),
                    };
                    newAttachment.Attachment_UniqueText = WebHelper.Helpers.StringHelper.ToUniqueStatement(newAttachment.AttachmentTitle_Ar + newAttachment.AttachmentTitle_En + newAttachment.AttachmentNote_Ar + newAttachment.AttachmentNote_En);
                    newFile.Attachments.Add(newAttachment);
                    ent.SaveChanges();
                    string imagePath = CustomAppSettings.DefaultFileImagePath;
                    string datePath = DateTime.Now.ToString("yyyy/MM/dd", CultureInfo.InvariantCulture);
                    imagePath = CustomAppSettings.FilesPathes + "/" + datePath + "/" + newAttachment.Attachment_ID + ".jpg";
                    Directory.CreateDirectory(Path.GetDirectoryName(CustomAppSettings.getActualPath(imagePath)));
                    System.IO.File.WriteAllBytes(imagePath, btBytes);
                    newAttachment.Attachment_Path = imagePath;
                    newAttachment.MimeType = "application/octet-stream";
                    //uploadAttachment(btBytes, newFile.File_ID);
                }
            }

            return Count.ToString();
        }
        catch
        {
            return "حدث خطأ في حفظ الملفات من الماسح الالكتروني , حاول مرة أخرى";
        }
    }

    /// <summary>
    /// this function will copy the file to the specified folder after creating its database field
    /// </summary>
    private void uploadAttachment(byte[] btImage, long folder_ID)
    {

        ////attachment
        //Attachment newAttachment = new Attachment
        //{
        //    Attachment_Order = 1,
        //    Attachment_Code = "",
        //    AttachmentTitle_Ar = newFile.FileTitle_Ar,
        //    AttachmentNote_Ar = newFile.FileTitle_Ar,
        //};
        //newAttachment.Attachment_UniqueText = WebHelper.Helpers.StringHelper.ToUniqueStatement(newAttachment.AttachmentTitle_Ar + newAttachment.AttachmentTitle_En + newAttachment.AttachmentNote_Ar + newAttachment.AttachmentNote_En);
        //newFile.Attachments.Add(newAttachment);
        //ent.SaveChanges();
        //string imagePath = CustomAppSettings.DefaultFileImagePath;
        //string datePath = DateTime.Now.ToString("yyyy/MM/dd", CultureInfo.InvariantCulture);
        //imagePath = CustomAppSettings.FilesPathes + "/" + datePath + "/" + newAttachment.Attachment_ID + Path.GetExtension(files[i]);
        //Directory.CreateDirectory(Path.GetDirectoryName(CustomAppSettings.getActualPath(imagePath)));
        //System.IO.File.Copy(files[i], CustomAppSettings.getActualPath(imagePath));
        //newAttachment.Attachment_Path = imagePath;
        //newAttachment.MimeType = "application/octet-stream";



        //BLAttachmentsPart blANew = new BLAttachmentsPart();
        //blANew.Attached_Date = DateTime.Now;
        //blANew.Attachment_ID = folder_ID;
        //blANew.Attachment_Part_Path = "";
        //blANew.Part_Notes = "";
        //blANew.ByEmployee_ID = GlobalVars.getLoginUser().CollectionEmployee_User_ID[0].Employee_ID;
        //blANew.AttachmentsPartsSearch = "";



        //blANew.SaveToDataBase(SaveToDataBaseType.Insert);




        //if (blANew.IsSaved)
        //{
        //    string strPath = getPartPathWithoutFile(blANew);
        //    string strFileName = System.Guid.NewGuid().ToString() + ".jpg";
        //    string strNewFileName = Path.Combine(strPath,strFileName );
        //    try
        //    {
        //        File.WriteAllBytes(strNewFileName, btImage);
        //    }
        //    catch
        //    {
        //    }

        //    blANew.Attachment_Part_Path = strFileName;
        //    blANew.SaveToDataBase(SaveToDataBaseType.Update);

        //    BLAttachmentsPart.updatePartsOrder(folder_ID);
        //    blANew = new BLAttachmentsPart { Part_ID = blANew.Part_ID };
        //    blANew.LoadFromDataBase();
        //    //BLAttachmentsPartsH blaOld = blANew.getHistory(GlobalVars.getOriginalUser().CollectionEmployee_User_ID[0].Employee_ID.Value, HistoryStatusEnum.New);
        //    //blaOld.SaveToDataBase(SaveToDataBaseType.Insert);

        //}

    }


    ///// <summary>
    ///// this function will take a saved obj and return its path
    ///// </summary>
    ///// <param name="obj">the object to get its path</param>
    ///// <returns>the path for the opject</returns>
    //private static string getPartPathWithoutFile(BLAttachmentsPart obj)
    //{
    //    BLServersPathe blNew = new BLServersPathe();

    //    blNew.Path_ID = 1;
    //    blNew.LoadFromDataBase();

    //    string strPath = blNew.Path;





    //    string strFullPath = "";

    //    getAttachmentsPartPath(obj, strPath, ref strFullPath);
    //    return strFullPath;
    //}


    ///// <summary>
    ///// this function will get the path of the part due to the path of the database
    ///// </summary>
    ///// <param name="obj">the object to get its path</param>
    ///// <param name="strPath">the path in the database</param>
    ///// <param name="strFullPath">the returned full path</param>
    //private static void getAttachmentsPartPath(BLAttachmentsPart obj, string strPath, ref string strFullPath)
    //{
    //    string strFilePath = "";
    //    if (obj.Attached_Date != null)
    //    {
    //        strFilePath = DateManipulationClass.getYear(obj.Attached_Date, "u").ToString("d4") + "\\"
    //            + DateManipulationClass.getMonth(obj.Attached_Date, "u").ToString("d2") + "\\" +
    //              DateManipulationClass.getDay(obj.Attached_Date, "u").ToString("d2") + "\\" +
    //              obj.Part_ID.ToString() + "\\";




    //    }
    //    else
    //    {
    //        strFullPath = "";
    //        return;
    //    }


    //    strFullPath = Path.Combine(strPath, strFilePath);

    //    if (!Directory.Exists(strFullPath))
    //        Directory.CreateDirectory(strFullPath);
    //}

    [OperationContract]
    public string HelloWorld()
    {
        //BLUser user = GlobalVars.getLoginUser();

        //if (user == null)
        //{
        //    return "خطأ , ليس مصرح لك بعرض هذه الرسالة";
        //}

        return "Hello World!";
    }


    [OperationContract]
    public string testParameters(string strTest)
    {
        return strTest.Substring(0, 10);
    }

	// Add more operations here and mark them with [OperationContract]
}
